#!/bin/bash

REMOTE_REPO="origin"
BRANCH_NAME="test"

handle_error() {
    echo "Error occurred: $1"
    exit 1
}

git pull $REMOTE_REPO $BRANCH_NAME || handle_error "Failed to pull remote repository"
git add . || handle_error "Failed to add changes to staging area"

if [ $# -ne 1 ]; then
   echo "Please use -m \"commit message\" format to add a commit message"
   exit 1
fi

timestamp=$(date "+%Y-%m-%d %H:%M:%S")
git commit -m "$1" || handle_error "Failed to create commit"
echo "Commit message: $1 - $timestamp"

latest_remote_tag=$(git describe --tags --abbrev=0 $REMOTE_REPO/$BRANCH_NAME) || handle_error "Failed to get latest remote tag"
major=$(echo $latest_remote_tag | cut -d'.' -f1)
minor=$(echo $latest_remote_tag | cut -d'.' -f2)
patch=$(($(echo $latest_remote_tag | cut -d'.' -f3) + 1))
new_version="$major.$minor.$patch"

git tag $new_version || handle_error "Failed to create new tag"
echo "New version tag: $new_version"

git push $REMOTE_REPO $BRANCH_NAME || handle_error "Failed to push changes to remote repository"
git push $REMOTE_REPO $BRANCH_NAME $new_version || handle_error "Failed to push new tag to remote repository"